﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace VRacer.Packets
{
    public static class PacketFactory
    {
        static private Dictionary<int, Type> _packets = new Dictionary<int, Type>();

        static PacketFactory()
        {
            Add(PacketType.Welcome, typeof(Packets.WelcomePacket));
            Add(PacketType.Login, typeof(Packets.LoginPacket));
            Add(PacketType.Ping, typeof(Packets.PingPacket));
            Add(PacketType.NewPlayer, typeof(Packets.NewPlayerPacket));
            Add(PacketType.PlayerMoving, typeof(Packets.PlayerMovingPacket));
            Add(PacketType.PlayerMoved, typeof(Packets.PlayerMovedPacket));
            Add(PacketType.GameState, typeof(Packets.GameStatePacket));
            Add(PacketType.PlayerCrashed, typeof(Packets.PlayerCrashedPacket));
            Add(PacketType.ContinueTurn, typeof(Packets.ContinueTurnPacket));
            Add(PacketType.PlayerCollision, typeof(Packets.PlayerCollisionPacket));
            Add(PacketType.PlayerRemoved, typeof(Packets.PlayerRemovedPacket));
            Add(PacketType.PlayerPosition, typeof(Packets.PlayerPositionPacket));
            Add(PacketType.Scores, typeof(Packets.ScoresPacket));
            Add(PacketType.Message, typeof(Packets.MessagePacket));
            Add(PacketType.PlayerLaps, typeof(Packets.PlayerLapsPacket));
        }

        /// <summary>
        /// Adds the specified packet type.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <param name="packetType">Type of the packet.</param>
        public static void Add(int type, Type packetType)
        {
            _packets[type] = packetType;
        }

        /// <summary>
        /// Adds the specified packet type.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <param name="packetType">Type of the packet.</param>
        public static void Add(PacketType type, Type packetType)
        {
            Add((int)type, packetType);
        }

        /// <summary>
        /// Gets the specified packet instance.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <returns></returns>
        public static PacketBase Get(int type)
        {
            Type packetType;
            if (_packets.ContainsKey(type))
            {
                packetType = _packets[type];
                return (PacketBase)packetType.GetConstructor(new Type[] { }).Invoke(null);
            }
            else
            {
                return new GenericPacket(type);
            }
        }
    }
}
